<template>
    <div>
    <!-- 三级列表展示 -->
    <Category :scene="scene"></Category>
    <!-- 三级分类底部数据模板 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin:10px 0;">
       <div v-show="scene==0">
        <el-button :disabled="!categoryStore.c3id" type="primary" size="default" :icon="Plus" @click="addAttr">添加属性</el-button>
       <el-table  border style="margin:10px 0 ;" :data="attrList">
        <el-table-column label="序号" width="80px" align="center" type="index" ></el-table-column>
        <el-table-column label="属性名称" width="150px" prop="attrName"></el-table-column>
        <el-table-column label="属性值列表">
            <template #="{row,$index}">
                <el-tag style="margin:0px 3px" class="ml-2" type="success" v-for="(attrVal,index) in row.attrValueList" :key="attrVal.id">{{attrVal.valueName}}</el-tag>
           </template>
        </el-table-column>
        <el-table-column label="操作" width="150px" >
            <template #="{row,$index}">
                <!-- 修改按钮 -->
                <el-button type="primary" size="small" :icon="Edit" @click="updateAttr(row)"></el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" size="small" :icon="Delete"   @click="removeAttr(row)"></el-button>
            </template>
        </el-table-column>

       </el-table>
       
       </div>
       <div v-show="scene==1">
        <el-form  ref="form" label-width="80px" :inline="true" >
            <el-form-item label="属性名">
                <el-input placeholder="请输入属性名字" v-model="attrParams.attrName"></el-input>
            </el-form-item>
        </el-form>
        <el-button type="primary" size="default"  :icon="Plus" :disabled="!attrParams.attrName" @click="addAttrValue">添加属性值</el-button>
        <el-button size="default" @click="cancel">取消</el-button>
        <el-table  border stripe style="margin:10px 0 ;" :data="attrParams.attrValueList">
            <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
            <el-table-column label="属性值名称">
               <template #="{row,$index}">
                <el-input :ref="(vc)=>(inputArr[$index] = vc)" @blur="toLook(row, $index)" v-if="row.flag" v-model="row.valueName" placeholder="请输入属性值名称"  clearable ></el-input>
                <div v-else @click="toEdit(row, $index)">{{row.valueName}}</div>
               </template>
                
            </el-table-column>
            <el-table-column label="操作">
                <template #="{row,$index}">
                    <el-button type="danger" :icon="Delete" size="small" @click="attrParams.attrValueList.splice($index,1)"></el-button>
                    
                </template>
            </el-table-column>
        </el-table>
        <el-button type="primary" size="default" :disabled="attrParams.attrValueList.length>0?false:true" @click="save" >保存</el-button>
        <el-button size="default" @click="cancel" >取消</el-button>
        
        
        
       </div>
       
    </el-card>
    
    </div>
</template>

<script setup lang="ts">
// 引入数据类型
import type {attrValueModel,attrValueListModel,attrModel,attrResponseData} from '@/api/product/attr/model/attr'
import { watch,ref,reactive, nextTick , onUnmounted } from 'vue';
import {reqAttrList,reqAddOrUpdateAttr,reqDeleteAttr,} from '@/api/product/attr/attr'
import { Delete, Edit, Search, Share, Upload ,Plus} from '@element-plus/icons-vue'
import { ElMessage } from "element-plus";
//引入lodash里面cloneDepp---深拷贝
import _ from "lodash";
 // 引入仓库
 import useCategoryStore from '@/stores/category'
// 获取仓库
let categoryStore = useCategoryStore()
// 定义存储平台数据
let attrList = ref<attrResponseData>([])
// 定义响应式变量,控制场景切换
let scene = ref<number>(0)
// 定义一个数组,将来存储el-input 实例
let inputArr = ref<any>([])
// 收集平台属性参数,定义将来添加或修改属性的参数
let attrParams = reactive<attrModel>({
  categoryId: '',
  categoryLevel: 3,
  attrName: "",
  attrValueList: [
    // {
    //   "attrId": 0,
    //   "id": 0,
    //   "valueName": "string"
    // }
  ],
})

// 监听三级分类id变化
watch(()=>categoryStore.c3id,()=>{
   if(categoryStore.c3id=='') return
   getAttrList()
})
// 获取商品属性请求封装成一个函数getAttrList
const getAttrList = async ()=>{
    let result = await reqAttrList(categoryStore.c1id,categoryStore.c2id,categoryStore.c3id)
      //存储数据---平台属性
    attrList.value = result
}

// 添加属性按钮的回调
const addAttr = ()=>{
    //每一次进入到添加|修改属性的时候，清空数据|同时把三级分类ID收集到
    Object.assign(attrParams,{
   categoryId: '',
  categoryLevel: categoryStore.c3id,
  attrName: "",
  attrValueList: [],

    })
    // 切换场景
    scene.value = 1
}

// 两个取消按钮的回调函数
const cancel =()=>{
    // 切换场景
    scene.value = 0
}

// 点击添加属性值按钮的回调
const addAttrValue = ()=>{
    attrParams.attrValueList.push({
        valueName:'',
        // 每创建一个input就添加一个flag属性做标记,用来切换编辑模式与查看模式
        flag:true
    })
    nextTick(()=>{
        // 最后一个聚焦
    inputArr.value[attrParams.attrValueList.length-1].focus()
})
}

// input失去焦点的回调
 const toLook = (row:attrValueModel,$index:number)=>{
    // 不能为空
    if(row.valueName.trim() ==''){
        ElMessage({
            type:'warning',
            message:"不能为空"
        })
    // 删除当前非法属性值
    attrParams.attrValueList.splice($index,1)
    return
    }

    // 属性值重名
    let repeat = attrParams.attrValueList.find((item)=>{
        if(row != item){
            return row.valueName === item.valueName
        }
    })
    if(repeat){
        ElMessage({
      type: "warning",
      message: `${repeat.valueName}重复?`,
    });
 // 删除当前非法属性值
 attrParams.attrValueList.splice($index,1)
 return
       }
//  变为查看模式
row.flag = false
 }

//  div点击,变成编辑模式
 const toEdit = (row:attrValueModel,$index:number) =>{
//    变为编辑模式
row.flag =true
nextTick(()=>{
    inputArr.value[$index].focus()
})
 }

//  点击保存按钮的回调
const save = async ()=>{
    // 不要flag属性
    attrParams.attrValueList.forEach((item)=>{
         if(item.hasOwnProperty('flag')){
             delete item.flag
         }
    })
    try {
       await reqAddOrUpdateAttr(attrParams)
    //   切换场景
    scene.value=0
    ElMessage({
        type:"success",
        message: attrParams.id ? "修改成功" : "添加成功",
    })
    // 获取最新数据
    getAttrList()
    } catch (error) {
        ElMessage({
      type: "success",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
    }
}

// 修改按钮回调
const updateAttr = (row:attrModel)=>{
    console.log(row);
    
    // 切换场景
    scene.value=1
    Object.assign(attrParams,_.cloneDeep(row))
}

// 删除按钮回调
const removeAttr =async (row:attrModel)=>{
  try {
   await reqDeleteAttr(row.id)
       //提示信息
       ElMessage({
      type: "success",
      message: `删除${row.attrName}成功`,
       duration:500,//约束提示信息的事件
    });
    // 获取最新数据
    getAttrList()
  } catch (error) {
    ElMessage({
      type: "error",
      message: `删除${row.attrName}失败`,
      duration:500
    });
  }
}

// 销毁钩子
onUnmounted(() => {
    // 路由跳转,组件会销毁,但仓库里的数据不会销毁,切回来依旧会显示
    // 在组件销毁时,清空仓库里的数据
    categoryStore.c1id=''
    categoryStore.c2id=''
    categoryStore.c3id=''
    categoryStore.c1List=[]
    categoryStore.c2List=[]
    categoryStore.c3List=[]
})
</script>

<style scoped>

</style>